﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService
{
    public partial class Service1 : ServiceBase
    {
        BBPA.BLL.Store bllStore = new BBPA.BLL.Store();
        BBPA.BLL.Plan_do bllPlan_do = new BBPA.BLL.Plan_do();
        BBPA.BLL.V_Orders bllV_Orders = new BBPA.BLL.V_Orders();
        BBPA.BLL.Store_Stat bllStore_Stat = new BBPA.BLL.Store_Stat();
        BBPA.BLL.Message bllMessage = new BBPA.BLL.Message();
        BBPA.BLL.SMS bllSMS = new BBPA.BLL.SMS();
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("已经启动");
        }

        protected override void OnStop()
        {
        }

        private void timer_main_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Plan_PAFee();
            //Plan_OrdersMoney();
            Plan_PreMonth();
            Plan_CheckGroupBuy();
        }
        /// <summary>
        /// 执行计划 PAFee：提醒缴纳联盟费
        /// </summary>
        void Plan_PAFee()
        {
            int planID = (int)EnumHelper.Plan.PAFee;
            if (DateTime.Now.Hour < 9 || bllPlan_do.GetRecordCount("PlanID=" + planID + " and datediff(day,[Dateandtime],getdate())=0") > 0) return;
            eventLog1.WriteEntry("开始执行计划 PAFee：提醒缴纳联盟费");
            //
            List<BBPA.Model.Store> listModelStore_3 = bllStore.GetModelList("datediff(day,PAFeeEndDate,getdate())=-2");//3天后过期
            foreach (BBPA.Model.Store store in listModelStore_3) NewMessage(store.UserID, "您的联盟服务费将在三天后到期，请您及时交纳，谢谢");
            List<BBPA.Model.Store> listModelStore_2 = bllStore.GetModelList("datediff(day,PAFeeEndDate,getdate())=-1");//2天后过期
            foreach (BBPA.Model.Store store in listModelStore_2) NewMessage(store.UserID, "您的联盟服务费将在二天后到期，请您及时交纳，谢谢");
            List<BBPA.Model.Store> listModelStore_1 = bllStore.GetModelList("datediff(day,PAFeeEndDate,getdate())=0");//1天后过期
            foreach (BBPA.Model.Store store in listModelStore_1) NewMessage(store.UserID, "您的联盟服务费将在明天到期，请您及时交纳，谢谢");
            //
            BBPA.Model.Plan_do modelPlan_do = new BBPA.Model.Plan_do();
            modelPlan_do.PlanID = planID;
            bllPlan_do.Add(modelPlan_do);
            eventLog1.WriteEntry("完成执行计划 PAFee：提醒缴纳联盟费。3天后到期数量" + listModelStore_3.Count + "，2天后到期数量" + listModelStore_2.Count + "，1天后到期数量" + listModelStore_1.Count + "");
        }
        /// <summary>
        /// 执行计划 OrdersMoney：提醒打货款
        /// </summary>
        void Plan_OrdersMoney()
        {
            int planID = (int)EnumHelper.Plan.OrdersMoney;
            if (DateTime.Now.Hour < 10 || bllPlan_do.GetRecordCount("PlanID=" + planID + " and datediff(day,[Dateandtime],getdate())=0") > 0) return;
            eventLog1.WriteEntry("开始执行计划 OrdersMoney：提醒打货款");
            //
            int do_num = 0;
            List<BBPA.Model.V_Orders> listV_Orders = bllV_Orders.GetModelList(" State=" + (int)EnumHelper.OrdersState.WaitMoney + "   and datediff(day,ExpectBuyDate,getdate())=-1");
            foreach (BBPA.Model.V_Orders v_Orders in listV_Orders) 
            {
                decimal ExpectPriceSum = BBPA.BLL.Orders.Get_Orders_ExpectSellPriceSum(v_Orders.id);
                if (ExpectPriceSum > 0)
                {
                    BBPA.Model.Store modelStore = bllStore.GetModel(v_Orders.StoreID);
                    decimal needMoreMoney = ExpectPriceSum + 100 - (modelStore.Account - modelStore.FrozenAccount);
                    if (needMoreMoney < 0) needMoreMoney = 0;
                    NewMessage(v_Orders.StoreUserID, "您本周订货总金额为" + StringPlus.showCoin(ExpectPriceSum) + "元，运费100元，共计需打款金额" + StringPlus.showCoin(needMoreMoney)+"，请在今天下午17时前打款，如未到帐则本周商品将累积至下周采购");
                    do_num++;
                }
                
            } 
            BBPA.Model.Plan_do modelPlan_do = new BBPA.Model.Plan_do();
            modelPlan_do.PlanID = planID;
            bllPlan_do.Add(modelPlan_do);
            eventLog1.WriteEntry("完成执行计划 OrdersMoney：提醒打货款。提醒数量" + do_num);
        }
        /// <summary>
        /// 执行计划 PreMonth：汇报上月情况
        /// </summary>
        void Plan_PreMonth()
        {
            int planID = (int)EnumHelper.Plan.PreMonth;
            if (DateTime.Now.Hour < 11 || bllPlan_do.GetRecordCount("PlanID=" + planID + " and datediff(month,[Dateandtime],getdate())=0") > 0) return;
            eventLog1.WriteEntry("开始执行计划 PreMonth：汇报上月情况");
            //
            List<BBPA.Model.Store_Stat> listModelStore_Stat = bllStore_Stat.GetModelList("RowID>0 and DateType=2 and datediff(month,[DateFrom],getdate())=1 and RowID in (select id from Store)");
            foreach (BBPA.Model.Store_Stat stat in listModelStore_Stat)
            {
                BBPA.Model.Store modelStore = bllStore.GetModel(stat.RowID);
                NewMessage(modelStore.UserID, "您上月共采购商品金额"+StringPlus.showCoin(stat.OrdersSellPrice)+"元，帐户余额为"+StringPlus.showCoin( modelStore.Account)+"元。");
            }
            //
            BBPA.Model.Plan_do modelPlan_do = new BBPA.Model.Plan_do();
            modelPlan_do.PlanID = planID;
            bllPlan_do.Add(modelPlan_do);
            eventLog1.WriteEntry("完成执行计划 PreMonth：汇报上月情况。提醒数量" + listModelStore_Stat.Count);
        }

        void NewMessage(int userID_,string content_)
        {
            bllMessage.NewMessage(0, 0, userID_, content_, true, true);
            eventLog1.WriteEntry("用户ID=" + userID_ + ",消息内容=" + content_);
        }

        void Plan_CheckGroupBuy()
        {
            int planID = (int)EnumHelper.Plan.PreMonth;
            if (DateTime.Now.Hour < 10 || bllPlan_do.GetRecordCount("PlanID=" + planID + " and datediff(day,[Dateandtime],getdate())=0") > 0) return;
            eventLog1.WriteEntry("开始核查订单");
            BBPA.BLL.GroupBuy bll = new BBPA.BLL.GroupBuy();
            DataTable dt = bll.GetOutGroupBuy();

            foreach (DataRow dr in dt.Rows)
            {
                BBPA.Model.Orders model = new BBPA.Model.Orders();
                BBPA.BLL.Orders bll_order = new BBPA.BLL.Orders();
                BBPA.BLL.Store bllStore = new BBPA.BLL.Store();
                BBPA.BLL.V_Orders bllList = new BBPA.BLL.V_Orders();
                BBPA.BLL.Orders_State_Log bllOrders_State_Log = new BBPA.BLL.Orders_State_Log();
                //List<BBPA.Model.V_Orders> modellist = bllList.GetModelList(" gbid=" + Master.id);

                if (Convert.ToInt32(dr["ExpectPay"]) > 0)
                {
                    model = bll_order.GetModel(Convert.ToInt32(dr["id"]));
                    BBPA.Model.Store modelStore = bllStore.GetModel(model.StoreID);
                    //1.支付货款
                    CallBak<int> callBak_BuySuccess = BBPA.BLL.Account_Change_Log.Add(EnumHelper.UserType.Store, Convert.ToInt32(dr["StoreID"]), EnumHelper.AccountChangeReason.Cancel_Orders, Convert.ToInt32(dr["id"]), 0);//扣孕婴店


                    //2.扣运费
                    CallBak<int> callBak_PayExpressMoney = BBPA.BLL.Account_Change_Log.Add(EnumHelper.UserType.Store, modelStore.id, EnumHelper.AccountChangeReason.Pay_ExpressMoney, Convert.ToInt32(dr["id"]), 0);


                    model.ExpressID = 0;
                    model.ExpressPrice = 0;
                    model.ExpressNumber = "";
                    model.State = (int)EnumHelper.OrdersState.NoGoods;
                    model.DateandtimeSend = DateTime.Now;
                    model.IsBuyMoneyOK = true;
                    bll_order.Update(model);

                    BBPA.BLL.User_Operate_Log.Add(Convert.ToInt32(dr["UserID"]), EnumHelper.TableName.Orders, Convert.ToInt32(dr["gbid"]), EnumHelper.OperateType.Update, "");
                    //订单状态日志
                    BBPA.Model.Orders_State_Log modelOrders_State_Log = new BBPA.Model.Orders_State_Log();
                    modelOrders_State_Log.OrdersID = Convert.ToInt32(dr["id"]);
                    modelOrders_State_Log.State = model.State;
                    int Orders_State_LogID_new = bllOrders_State_Log.Add(modelOrders_State_Log);
                    BBPA.BLL.User_Operate_Log.Add(Convert.ToInt32(dr["UserID"]), EnumHelper.TableName.Orders_State_Log, Orders_State_LogID_new, EnumHelper.OperateType.Add, "");
                    //扣除运费后，孕婴店金额发生变化，所以要重新获取modelStore
                    modelStore = bllStore.GetModel(model.StoreID);
                    //通知孕婴店
                    BBPA.BLL.Message bllMessage = new BBPA.BLL.Message();
                    bllMessage.NewMessage(0, Convert.ToInt32(dr["UserID"]), modelStore.UserID,
                        "您参与的团购已失败，共计金额" + StringPlus.showMoney(model.ExpectPay) + "元，运费100元，已返回您的账户，您帐户剩余金额为" + modelStore.Account + "元", true, true);

                }

                bll_order.Delete(Convert.ToInt32(dr["id"]));
                Maticsoft.DBUtility.DbHelperSQL.ExecuteSql("delete from Orders_Goods where  OrdersID=" + Convert.ToInt32(dr["id"]));



            }


            
        }
    }
}
